package com.dingding.gmall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.dingding.gmall.auth.feign.MemberFeignService;
import com.dingding.gmall.auth.feign.ThirdPartFeignService;
import com.dingding.gmall.auth.query.UserLoginQuery;
import com.dingding.gmall.auth.query.UserRegistQuery;
import com.dingding.gmall.common.constant.AuthServerConstant;
import com.dingding.gmall.common.dto.MemberDTO;
import com.dingding.gmall.common.exception.BizCodeEnum;
import com.dingding.gmall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author liudingding
 * @ClassName LoginController
 * @description
 * @date 2021/6/25 12:27 上午
 */

@Controller
@Slf4j
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

//    @GetMapping({"/","/login.html"})
//    public String loginPage(HttpSession session) {
//        //从session先取出来用户的信息，判断用户是否已经登录过了
//        //如果用户没登录那就跳转到登录页面
//        return "login";
//    }

//    @GetMapping(value = "/regist.html")
//    public String registPage(HttpSession session) {
//        //从session先取出来用户的信息，判断用户是否已经登录过了
//        Object attribute = session.getAttribute(null);
//        //如果用户没登录那就跳转到登录页面
//        return "/regist";
//    }

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        String authKey = AuthServerConstant.SMS_CODE_CACHE_PRERFIX + phone;
        String redisCode = redisTemplate.opsForValue().get(authKey);
        if (StringUtils.isNotBlank(redisCode)){
            long redisTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - redisTime < 60 * 1000) {
                return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMsg());
            }
        }
        //验证码
        String code = UUID.randomUUID().toString().substring(0,5) +"_"+ System.currentTimeMillis();
        //redis缓存验证码，防止60s内重复发送
        redisTemplate.opsForValue().set(authKey, code, 10, TimeUnit.MINUTES);
        //发送短信
//        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistQuery userRegistQuery, BindingResult bindingResult, RedirectAttributes model){
        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            Map<String, String> map = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (key1 ,key2) -> key2));
            model.addFlashAttribute("errors",map);
            //校验出错，转发到注册页
            return "redirect:/regist.html";
        }
        //校验验证码
        String code = userRegistQuery.getCode();
        String codeRedisKey = AuthServerConstant.SMS_CODE_CACHE_PRERFIX + userRegistQuery.getPhone();
        String codeRedisValue = redisTemplate.opsForValue().get(codeRedisKey);
        //验证码是否过期
        if (StringUtils.isBlank(codeRedisValue)){
            return redirect(model, BizCodeEnum.CODE_EXPIRED.getMsg());
        } else {
            String redisCode = codeRedisValue.split("_")[0];
            //验证码是否通过
            if (StringUtils.equals(code, redisCode)) {
                //删除验证码
                redisTemplate.delete(codeRedisKey);
                //远程调用进行注册
                R r = memberFeignService.register(userRegistQuery);
                if (r.getCode() == 0) {
                    //成功
                    //注册成功回到登录页
                    log.info("用户注册成功");
                    return "redirect:/login.html";
                } else {
                    //失败
                    String msg = r.getData("msg", new TypeReference<String>() {});
                    return redirect(model, msg);
                }
            } else {
                return redirect(model, BizCodeEnum.CODE_ERROR.getMsg());
            }
        }
    }

    private String redirect(RedirectAttributes model, String msg){
        Map<String, String> errorsMap = new HashMap<>();
        errorsMap.put("code", msg);
        model.addFlashAttribute("errors",errorsMap);
        return "redirect:/regist.html";
    }

    @PostMapping("/login")
    public String login(UserLoginQuery query, RedirectAttributes model, HttpSession session){
        R r = memberFeignService.login(query);
        if (r.getCode() == 0) {
            MemberDTO data = r.getData("data", new TypeReference<MemberDTO>() {});
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://127.0.0.1:20000";
        } else {
            Map<String, String> errorsMap = new HashMap<>();
            errorsMap.put("code", r.getData("msg", new TypeReference<String>(){}));
            model.addFlashAttribute("errors",errorsMap);
            return "redirect:/login.html";
        }
    }

    @GetMapping(value = "/login.html")
    public String loginPage(HttpSession session) {
        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        //如果用户没登录那就跳转到登录页面
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://127.0.0.1:20000";
        }
    }

    @GetMapping(value = "/logout.html")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(AuthServerConstant.LOGIN_USER);
        request.getSession().invalidate();
        return "redirect:http://127.0.0.1:20000";
    }
}
